<?php
namespace Home\Controller;
use Think\Controller;
class RecreationController extends Controller {
	public function _initialize()
    {
        //未登录、登录超时、长时间未动
    	if (empty($_SESSION['uid']) || time() > $_SESSION['overtime'] || empty($_SESSION['overtime']) ) {

    		$this->redirect('Common/login');
    	}

        session('overtime',(time()+60*60*C('overtime')));

    }


    public function pk10(){
    	$this->display();
    }


    /**
     * [ctrl_getssc 异步获取数据]
     * @return [type] [description]
     */
    public function ctrl_getssc(){
        if(IS_AJAX){
            $uid = $_SESSION['uid'];

            $m_applytask = M("Applytask");
            $m_gamessc = M('Game_ssc');

            $src = C('KCW_SRC');//api接口地址
            //防止GET本地缓存，增加随机数
            $src .= '&rows=1'.(strpos($src,'?')>0 ? '&':'?').'_='.time();
            $html = file_get_contents($src);
            $json = json_decode($html,true);

            if (isset($json['rows'])){
                $openArr = array();
                $expect = preg_replace("/^(\d{8})(\d{3})$/","\\1-\\2",$json['data']['0']['expect']);
                $expect_arr = explode('-', $expect);
                $openArr['code'] = $expect_arr['0'];
                $openArr['codenum'] = $expect_arr['1'];
                $openArr['opencode'] = str_replace(","," ",$json['data']['0']['opencode']);

                //查找是否已经存在最新一条数据
                $where_ssc['code'] = $expect_arr['0'];
                $where_ssc['codenum'] = $expect_arr['1'];
                $sscInfo = $m_gamessc->where($where_ssc)->getfield('id');

                if (!$sscInfo) {
                    //添加数据库
                    $add['code'] = $expect_arr['0'];
                    $add['codenum'] = $expect_arr['1'];
                    $add['num'] = $json['data']['0']['opencode'];
                    $add['createtime'] = $json['data']['0']['opentime'];
                    $add['str_time'] = $json['data']['0']['opentimestamp'];
                    $m_gamessc->add($add);

                    //添加长龙
                    func_dragon($json['data']['0']['opencode']);

                }

                // 判断用户的结果
                $where_apply['user_id'] = $uid;
                $where_apply['status'] = 0;
                $applytaskInfo = $m_applytask->where($where_apply)->order('id desc')->find();

                if (!empty($applytaskInfo['user_guess'])) {

                    if ($applytaskInfo['type'] == 1) {
                        $where_touzhu['code'] = $applytaskInfo['code'];
                        $where_touzhu['codenum'] = $applytaskInfo['codenum'];
                        $gamesscInfo = $m_gamessc->where($where_touzhu)->find();
                        if ($gamesscInfo['id']) {
                            // 更新用户投注信息
                            $save['opencode'] = $gamesscInfo['num'];
                            $m_applytask->where(array('id'=>$applytaskInfo['id']))->save($save);

                            // 判断用户结果
                            $user_res = userWinOrLose($applytaskInfo['id']);

                            
                        }
                    }
                    
                }

                //显示长龙
                $show_dragon = array();
                $show_dragon = show_dragon();
                
                // 最新一期结果
                $this->ajaxReturn(array(
                    'code'=>1,
                    'msg' => '成功',
                    'newopencode'=>$openArr,
                    'show_dragon'=>$show_dragon,
                    'user_res'=>$user_res
                ));
                            

            }else{
                $this->ajaxReturn(array(
                    'code'=>0,
                    'msg' => '数据错误，请刷新页面'
                ));
            }
        }else{
            $this->redirect('Common/BadRequest');
        }
    }

    public function ssc(){
        $uid = $_SESSION['uid'];

        $m_applytask = M("Applytask");
        $m_gamessc = M('Game_ssc');

        $now = date('Y-m-d H:i:s');
        

        $src = C('KCW_SRC');//api接口地址
        //防止GET本地缓存，增加随机数
        $src .= '&rows=1'.(strpos($src,'?')>0 ? '&':'?').'_='.time();
        $html = file_get_contents($src);
        $json = json_decode($html,true);

        if (isset($json['rows'])){
            $newCode = array();
            // echo "<pre>";
            // print_r($json);die();
            foreach($json['data'] as $key => $r){
                $expect = preg_replace("/^(\d{8})(\d{3})$/","\\1-\\2",$r['expect']);
                $opencode = $r['opencode'];
                $opentime = $r['opentime'];

                $expect_arr = explode('-', $expect);

                $where_ssc['code'] = $expect_arr['0'];
                $where_ssc['codenum'] = $expect_arr['1'];
                $sscInfo = $m_gamessc->where($where_ssc)->getfield('id');
                
                if (!$sscInfo) {
                    $add['code'] = $expect_arr['0'];
                    $add['codenum'] = $expect_arr['1'];
                    $add['num'] = $opencode;
                    $add['createtime'] = $opentime;
                    $add['str_time'] = $r['opentimestamp'];

                    $m_gamessc->add($add);

                    // 添加长龙
                    func_dragon($opencode);
                }

                
                if ($key == 0) {//最新一期结果
                    $newCode['code'] = $expect_arr['0'];
                    $newCode['codenum'] = sprintf ( "%03d",$expect_arr['1']);
                    $newCode['opencode'] = str_replace(","," ",$opencode);
                    $newCode['opentime'] = $opentime;
                    $newCode['strtime'] = $r['opentimestamp'];
// print_r($r['opentimestamp']);
                    
                    if ($now >= date("Y-m-d 10:00:00") && $now < date("Y-m-d 22:00:00")) {
                        $nextfeng = $newCode['strtime']-60 + 9*60;
                        $nextime = $newCode['strtime'] -60 + 10*60;
                    }elseif ($now >= date("Y-m-d 22:00:00") || $now < date("Y-m-d 02:00:00") ) {
                        $nextfeng = $newCode['strtime']-60 + 4*60;
                        $nextime = $newCode['strtime'] -60 + 5*60;
                    }else{
                        $nextfeng = strtotime(date("Y-m-d 10:01:00"));
                        $nextime = strtotime(date("Y-m-d 10:02:00"));
                    }
                    
                }
            }
        }else{
            $this->redirect('Recreation/ssc');
        }


// echo "<br>";
// print_r($)
// print_r($nextfeng);die();
// print_r($nextime);
        //显示长龙
        $show_dragon = array();
        $show_dragon = show_dragon();

        $where_apply['user_id'] = $uid;
        $where_apply['status'] = 0;
        $applytaskInfo = $m_applytask->where($where_apply)->order('id desc')->find();
        if (empty($applytaskInfo['id'])) {
            $score_recreation = 0;
        }else{
            if (empty($applytaskInfo['user_guess'])) {
                $score_recreation = $applytaskInfo['num'];
            }else{
                $score_recreation = 0;
            }
        }

        // 最新投注的任务（已投注）
        // $where_my['user_id'] = $uid;
        // $where_my['user_guess'] = array('NEQ','');
        // $mynewtask = $m_applytask->where($where_my)->order('id desc')->field('code,codenum,opencode,user_guess')->find();
        // $mynewtask['opencode'] = str_replace(',', ' ', $mynewtask['opencode']);
        // $mynewtask['user_guess'] = explode('-', $mynewtask['user_guess']);

        // 今日输赢
        $starttime = strtotime(date('Y-m-d 00:00:00'));
        $endtime = strtotime(date('Y-m-d 23:59:59'));
        $where_today['user_id'] = $uid;
        $where_today['status'] = 1;
        $where_today['createtime'] = array('between',array($starttime,$endtime));
        $where_today['winlose'] = 0;//输
        $count_lose = $m_applytask->where($where_today)->count()+0;
        $total_lose = $count_lose * (-1000);

        $where_today['winlose'] = 1;//赢
        $count_win = $m_applytask->where($where_today)->count()+0;
        $total_win = $count_win * 998;

        $total_today = $total_lose + $total_win;
        // echo "<pre>";print_r($total_today);die();
        
        $strtime['start_time'] = strtotime(date("Y-m-d 10:00:00"));
        $strtime['end_time'] = strtotime(date("Y-m-d 22:00:00"));
        $strtime['endend_time'] = strtotime(date("Y-m-d 02:00:00"));

        $nextCode = sprintf ( "%03d",$newCode['codenum'] +1);
        $this->assign('strtime',json_encode($strtime));
        $this->assign('nextfeng',$nextfeng);
        $this->assign('nextime',$nextime);
        $this->assign('nextCode',$nextCode);
        $this->assign('newCode',$newCode);
        $this->assign('uid',$uid);
        $this->assign('score_recreation',$score_recreation);
        $this->assign('show_dragon',$show_dragon);
        // $this->assign('mynewtask',$mynewtask);
        $this->assign('total_today',$total_today);
    	$this->display();
    }



    /**
     * [ctrl_sscPlay 整合 确定操作]
     * @return [type] [description]
     */
    public function ctrl_sscPlay(){
        if(IS_AJAX){
            $uid = $_REQUEST['uid'];
            $money = trim($_REQUEST['money']);
            $whichBall = $_REQUEST['whichBall'];
            $code = $_REQUEST['code'];
            $codenum = $_REQUEST['codenum'];

            $m_applytask = M('Applytask');

            $where_apply['user_id'] = $uid;
            $where_apply['status'] = 0;
            $applytaskInfo = $m_applytask->where($where_apply)->order('id desc')->find();
            if (empty($applytaskInfo['id'])) {
                $this->ajaxReturn(array(
                    'code'=>0,
                    'msg' => '您没有正在进行中的任务，请重新申请'
                ));
            }else{
                if (!empty($applytaskInfo['user_guess'])) {
                    $this->ajaxReturn(array(
                        'code'=>0,
                        'msg' => '请耐心等待'
                    ));
                }else{
                    $save['type'] = 1;
                    $save['code'] = $code;
                    $save['codenum'] = $codenum;
                    $save['user_guess'] = $whichBall;

                    $where_save['id'] = $applytaskInfo['id'];
                    $res = $m_applytask->where($where_save)->save($save);
                    if ($res) {

                        $mycode = $code.$codenum;
                        $this->ajaxReturn(array(
                            'code'=>1,
                            'msg' => '操作成功，请耐心等待结果',
                            'mycode'=>$mycode
                        ));
                    }else{
                        $this->ajaxReturn(array(
                            'code'=>0,
                            'msg' => '操作失败，请重新操作'
                        ));
                    }
                }
            }

        }else{
            $this->redirect('Common/BadRequest');
        }
    }


    /**
     * [history 历史记录]
     * @return [type] [description]
     */
    public function history(){
        $uid = $_SESSION['uid'];

        $m_applytask = M('Applytask');

        $where['user_id'] = $uid;
        $count = $m_applytask->where($where)->count();
        $Page  = new \Think\Page($count,20);
        $show  = $Page->show();

        $applytaskList = $m_applytask->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach ($applytaskList as $key => $value) {
            $guessArr = array();
            $guessArr = explode('-', $value['user_guess']);
            $applytaskList[$key]['page'] = $guessArr[0];
            $applytaskList[$key]['ball'] = $guessArr[1];
            $applytaskList[$key]['which'] = $guessArr[2];

        }

        $this->assign('page',$show);
        $this->assign('applytaskList',$applytaskList);

        $this->display();
    }

}